<template>
    <div class="my-devices-container">
      <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="闲置" :value="0"></el-option>
            <el-option label="已分配" :value="1"></el-option>
            <el-option label="故障" :value="2"></el-option>
            <el-option label="维修中" :value="3"></el-option>
            <el-option label="报废" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>我的设备</span>
          </div>
        </template>
  
        <el-table :data="deviceList" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="设备ID" width="80"></el-table-column>
          <el-table-column prop="name" label="设备名称" width="120"></el-table-column>
          <el-table-column prop="type" label="类型" width="100"></el-table-column>
          <el-table-column prop="location" label="位置" width="150"></el-table-column>
          <el-table-column prop="temperatureRange" label="温度范围" width="100"></el-table-column>
          <el-table-column prop="voltageRange" label="电压范围" width="100"></el-table-column>
          
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{row}">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180">
            <template #default="{row}">
              <el-button size="small" @click="handleInspect(row)">巡检</el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="handleWarning(row)"
              >预警</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleReportIssue(row)"
                v-if="row.status !== 2 && row.status !== 4"
              >
                报修
              </el-button>
              
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
      </el-card>

      <el-dialog v-model="showInspectForm" title="设备巡检" width="600px">
        <el-form :model="inspectForm" label-width="120px">
          <el-form-item label="当前电压(V)">
            <el-input-number v-model="inspectForm.voltage" :precision="2" :step="0.1" :min="0" />
          </el-form-item>
          <el-form-item label="当前温度(℃)">
            <el-input-number v-model="inspectForm.temperature" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="巡检描述">
            <el-input v-model="inspectForm.description" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="上传附件">
            <el-upload
              action="#"
              :limit="3"
              accept="image/png, image/jpeg"
              :file-list="inspectForm.attachments"
              :auto-upload="false"
              :on-change="handleInspectAttachmentChange"
              multiple
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传巡检相关图片，最多3张</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showInspectForm = false">取消</el-button>
          <el-button type="primary" @click="submitInspect">提交</el-button>
        </template>
      </el-dialog>
      
      <!-- 预警对话框 -->
      <el-dialog v-model="showWarningForm" title="设备预警" width="600px">
        <el-form :model="warningForm" label-width="120px">
          <el-form-item label="预警等级">
            <el-radio-group v-model="warningForm.level">
              <el-radio-button :label="1">低</el-radio-button>
              <el-radio-button :label="2">中</el-radio-button>
              <el-radio-button :label="3">高</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="预警描述">
            <el-input v-model="warningForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showWarningForm = false">取消</el-button>
          <el-button type="primary" @click="submitWarning">提交</el-button>
        </template>
      </el-dialog>
      
      <!-- 报修对话框 -->
      <el-dialog v-model="showRepairForm" title="设备报修" width="600px">
        <el-form :model="repairForm" label-width="120px">
          <el-form-item label="紧急程度">
            <el-select v-model="repairForm.priority" placeholder="请选择紧急程度">
              <el-option label="低" :value="1"></el-option>
              <el-option label="中" :value="2"></el-option>
              <el-option label="高" :value="3"></el-option>
              <el-option label="紧急" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="问题描述">
            <el-input v-model="repairForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showRepairForm = false">取消</el-button>
          <el-button type="primary" @click="submitRepair">提交</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage,ElMessageBox } from 'element-plus';
  import {  getDevicesByEmployee, 
  reportDeviceIssue,
  submitInspection,
  deviceWarning, } from '@/api/device';
  import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus';
const searchForm = reactive({
  name: '',
  status: null,
  allocatedEmployee: null
});
  const deviceList = ref([]);
  const loading = ref(false);
  const currentDeviceId = ref(null);
  const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});
// 新增状态和表单
const showInspectForm = ref(false);
const showWarningForm = ref(false);
const showRepairForm = ref(false);

const inspectForm = reactive({
  deviceId: null as number | null,
  voltage: 0,
  temperature: 0,
  description: '',
  attachments: [] as UploadUserFile[]
});

const warningForm = reactive({
  deviceId: null as number | null,
  level: 2, // 默认中级
  description: ''
});

const repairForm = reactive({
  deviceId: null as number | null,
  priority: 2, // 默认中级
  description: ''
});
  // 获取当前用户的设备列表
  const fetchMyDevices = async () => {
    try {
      loading.value = true;
      const res = await getDevicesByEmployee({
        pageNum: pagination.current,
      pageSize: pagination.size,
      name: searchForm.name,
      status: searchForm.status
      });
      deviceList.value = res.data.records;
      pagination.total = res.data.total;
    } catch (error) {
      ElMessage.error('获取设备列表失败');
    } finally {
      loading.value = false;
    }
  };
  
  // 状态文本映射
  const getStatusText = (status) => {
    const statusMap = {
      0: '闲置',
      1: '已分配',
      2: '故障',
      3: '维修中',
      4: '报废'
    };
    return statusMap[status] || '未知';
  };
  
  // 状态标签类型
  const getStatusTagType = (status) => {
    const typeMap = {
      0: 'info',
      1: 'success',
      2: 'danger',
      3: 'warning',
      4: ''
    };
    return typeMap[status] || '';
  };
  

    // 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchMyDevices();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.status = null;
  pagination.current = 1;
  fetchMyDevices();
};
// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.size = val;
  fetchMyDevices();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.current = val;
  fetchMyDevices();
};  
// 处理巡检附件变化
const handleInspectAttachmentChange = (file: UploadFile, fileList: UploadFiles) => {
  inspectForm.attachments = fileList;
};

// 打开巡检表单
const handleInspect = (row: any) => {
  currentDeviceId.value = row.id;
  inspectForm.deviceId = row.id;
  inspectForm.voltage = 0;
  inspectForm.temperature = 0;
  inspectForm.description = '';
  inspectForm.attachments = [];
  showInspectForm.value = true;
};

// 提交巡检
const submitInspect = async () => {
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append('inspection', new Blob([JSON.stringify({
    deviceId: inspectForm.deviceId,
    voltage: inspectForm.voltage,
    temperature: inspectForm.temperature,
    description: inspectForm.description
})], { type: 'application/json' }));
    inspectForm.attachments.forEach(file => {
      if (file.raw) {
        formData.append('attachments', file.raw);
      }
    });
    
    await submitInspection(formData);
    ElMessage.success('巡检记录提交成功');
    showInspectForm.value = false;
    fetchMyDevices();
  } catch (error) {
    ElMessage.error('提交巡检记录失败');
  } finally {
    loading.value = false;
  }
};

// 打开预警表单
const handleWarning = (row: any) => {
  currentDeviceId.value = row.id;
  warningForm.deviceId = row.id;
  warningForm.level = 2;
  warningForm.description = '';
  showWarningForm.value = true;
};

// 提交预警
const submitWarning = async () => {
  try {
    loading.value = true;
    await deviceWarning({
      deviceId: warningForm.deviceId,
      level: warningForm.level,
      description: warningForm.description
    });
    ElMessage.success('预警提交成功');
    showWarningForm.value = false;
    fetchMyDevices();
  } catch (error) {
    ElMessage.error('提交预警失败');
  } finally {
    loading.value = false;
  }
};

// 打开报修表单
const handleReportIssue = (row: any) => {
  currentDeviceId.value = row.id;
  repairForm.deviceId = row.id;
  repairForm.priority = 2;
  repairForm.description = '';
  showRepairForm.value = true;
};

// 提交报修
const submitRepair = async () => {
  try {
    loading.value = true;
    await reportDeviceIssue({
      deviceId: repairForm.deviceId,
      priority: repairForm.priority,
      description: repairForm.description
    });
    ElMessage.success('报修申请提交成功');
    showRepairForm.value = false;
    fetchMyDevices();
  } catch (error) {
    ElMessage.error('提交报修申请失败');
  } finally {
    loading.value = false;
  }
};

  
  onMounted(() => {
    fetchMyDevices();
  });
  </script>
  
  <style scoped>
  .my-devices-container {
    padding: 20px;
  }
  
  .box-card {
    margin-bottom: 20px;
  }
  </style>